#include <xp/bas/fio.h> 
#include <xp/bas/stdio.h> 
#include <xp/bas/string.h> 

int xp_main (int argc, xp_char_t* argv[])
{
	xp_fio_t src, dst;
	xp_mchar_t buf[10000];
	xp_ssize_t n;
	xp_char_t* src_file, * dst_file;
	int dst_mode;

	if (argc != 3 && argc != 4) {
		xp_printf (XP_TEXT("usage: %s [-a] source_file destination_file\n"), argv[0]);
		return -1;
	}

	if (argc == 4 && xp_strcmp(argv[1], XP_TEXT("-a")) != 0) {
		xp_printf (XP_TEXT("usage: %s [-a] source_file destination_file\n"), argv[0]);
		return -1;
	}

	src_file = argv[(argc == 3)? 1: 2];
	dst_file = argv[(argc == 3)? 2: 3];

	if (xp_fio_open(&src, src_file, XP_FIO_READ, 0) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open %s\n"), src_file);
		return -1;
	}

	dst_mode = XP_FIO_WRITE | XP_FIO_CREATE | XP_FIO_TRUNCATE;
	if (argc == 4) {
		dst_mode |= XP_FIO_APPEND;
		dst_mode &= ~XP_FIO_TRUNCATE;
	}

	if (xp_fio_open(&dst, dst_file, dst_mode, 0) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open %s\n"), dst_file);
		return -1;
	}

	while (1) {
		n = xp_fio_read (&src, buf, xp_sizeof(buf) - 1);
		if (n == -1) {
			xp_printf (XP_TEXT("read error\n"));
			break;
		}
		if (n == 0) break;

		n = xp_fio_write (&dst, buf, n);
		if (n == -1) {
			xp_printf (XP_TEXT("write error\n"));
			break;
		}
	}

	xp_fio_close (&src);
	xp_fio_close (&dst);
	return 0;
}
